// Copyright (c) 2011 Blue Onion Software, All rights reserved
using System;
using System.Collections.Generic;
using System.Xml;

namespace BlueOnionSoftware.Bloget
{
    internal class XmlRpcMethodResponse
    {
        private int faultCode;
        private string faultString;
        private readonly List<XmlRpcValue> parameters = new List<XmlRpcValue>();

        internal int FaultCode
        {
            get { return faultCode; }
            set { faultCode = value; }
        }

        internal string FaultString
        {
            get { return faultString; }
            set { faultString = value; }
        }

        internal void AddParam(XmlRpcValue param)
        {
            Throw.IfNull(param, "param");
            parameters.Add(param);
        }

        internal void Serialize(XmlWriter writer)
        {
            Throw.IfNull(writer, "writer");

            writer.WriteStartDocument();
            writer.WriteStartElement("methodResponse");

            if (faultString != null)
            {
                writer.WriteStartElement("fault");
                writer.WriteStartElement("value");

                var faultStruct = new XmlRpcStruct();
                faultStruct.Add(new XmlRpcMember("faultCode", faultCode));
                faultStruct.Add(new XmlRpcMember("faultString", faultString));

                faultStruct.Serialize(writer);
            }

            else
            {
                writer.WriteStartElement("params");

                if (parameters.Count == 0)
                {
                    throw new InvalidOperationException("XmlRpcMethodResponse.Serialize has no parameters");
                }

                foreach (var value in parameters)
                {
                    writer.WriteStartElement("param");
                    value.Serialize(writer);
                    writer.WriteEndElement();
                }
            }

            writer.WriteEndDocument();
            writer.Flush();
        }
    }
}